/**
 * Created by JetBrains WebStorm.
 * User: mumble
 * Date: 3/7/12
 * Time: 10:37 PM
 * To change this template use File | Settings | File Templates.
 */
var  sys = require('util'),
    path = require('path'),
    WebSocketServer = require('ws').Server,
    express = require('express'),
    app = express.createServer(),
    gameObj = require('./lib/gameobject'),
    match = require('./lib/match').Match;

const SERVER_VERSION = '0.1';

var _  = match.incl;

const DISTCONNEDTED =  0,
    IDLE = 1,
    CONNECTED = 2,
    HANDSHAKING = 3,
    JOINED = 4;

const DEFAULT_OPTIONS = {
    isDebug :              true,
    name :                  'Arena game',
    host :                  '192.168.11.12',
    http_port:              80,
    ws_port :               21000,
    max_connections :       1000,
    max_players :           10
};



function Main()
{
    gameServer = null;
    webServer = null;

    startGameServer();
    startWebServer();
}

function startGameServer()
{

    var mapConnection = {},
        number_connection = 0,
        number_room = 0,
        mapRoom = {}
        game_server = null;


    game_server = new WebSocketServer({host: DEFAULT_OPTIONS.host, port : DEFAULT_OPTIONS.ws_port});

    game_server.on('connection', function(conn) {
        console.log('Co ket noi toi');
        var connection_id = 0;
        var disconnect_reason = 'Closed by client';
        var last_ping = 0;
        var last_pong = 0;

        var message_queue = [];


        conn.set_client_info = function(info) {
            conn.name = info.name;
            conn.score = info.score;
            conn.weapon_type = info.weapon_type;
        };
        conn.queue = function(msg) {
            if(conn.STATE = JOINED)
                message_queue.push(msg);
        };
        conn.post_msg = function(msg) {
            var package = JSON.stringify(msg);
            conn.send(package);
        };

        conn.flush_queue = function() {
            var msg = null,
                data_sent = 0,
                package_data = [];

            while( (msg = message_queue.shift()))
            {
                var data = JSON.stringify(msg);
                package_data.push(data);
                data_sent += data.length;
            }
            this.send('['+GAME_PACKAGE+',['+package_data.join(',')+']]');
            message_queue = [];

        };
        conn.setState = function(new_state) {
            switch(new_state)
            {
                case CONNECTED :
                    while(mapConnection[++connection_id]);

                    conn.id = connection_id;
                    conn.player = null;
                    conn.player_name = null;
                    conn.state = IDLE;
                    mapConnection[connection_id] = conn;
                    break;


            }

        }

        conn.on('message', function(data, flags) {
            console.log('Co ban tin toi');
            var package = null;
            try
            {
                package = JSON.parse(data);
            }
            catch(e)
            {
                console.log('Ban tin loi');
                return;
            }

            switch(package[0])
            {
                case PING_PACKAGE:
                    last_pong = get_time();
                    break;
                case GAME_PACKAGE:
                    process_game_message([package[1], conn.player]);
                    break;
                case CONTROL_PACKAGE:
                    process_control_message([package[1], conn]);
                    break;

            }

        });

        conn.setState(CONNECTED);





    });

    return game_server;

}

process_control_message = match(
    [[CTRL_CMD_CLIENT_INFO,Object], _],
    function(info, conn)
    {
        conn.set_client_info(info);
    },
    [[CTRL_CMD_CREATE_ROOM, String], _],
    function(room_name, conn)
    {

    },
    [[CTRL_CMD_CLIENT_JOIN_ROOM, String], _],
    function(room_id, conn)
    {

    },
    [[CTRL_CMD_CLIENT_LOGIN, String, String],_],
    function(username, password, conn)
    {
        console.log('User login '+username + ':'+password);
    },
    [[CTRL_CMD_CLIENT_CHAT, String], _],
    function(message, conn)
    {
        conn.send(message);
    }



);

process_game_message = match (
    [[CTRL_CMD_CLIENT_INFO,Object], _, _],
    function(info, conn)
    {
        conn.set_client_info(info);
    }
);

function startWebServer()
{
    app.use(express.static(__dirname+'/public'));
}

/**
 *  Returns current time stamp
 */
function get_time() {
    return new Date().getTime();
}


Main();








